package utils

import (
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

// @title    PathExists
// @description   文件目录是否存在
// @auth                     （2020/04/05  20:22）
// @param     path            string
// @return    err             error

func PathExists(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}
	return false
}

func MergeFileShell(src, outfile string) {
	partList, err := filepath.Glob(src)

	if err != nil {
		return
	}

	var str strings.Builder
	str.WriteString("cat ")
	for _, v := range partList {
		str.WriteString(v)
		str.WriteString(" ")
	}
	str.WriteString(">")
	str.WriteString(outfile)
	cmd := exec.Command("bash", "-c", str.String())
	cmd.Run()
}

func MergeFile(src, outfile string) {
	fi, err := os.OpenFile(outfile, os.O_CREATE|os.O_TRUNC|os.O_RDWR, os.ModePerm)
	if err != nil {
		return
	}

	partList, err := filepath.Glob(src)
	if err != nil {
		return
	}

	for _, v := range partList {
		f, err := os.OpenFile(v, os.O_RDONLY, os.ModePerm)
		if err != nil {
			continue
		}

		b, err := ioutil.ReadAll(f)
		if err != nil {
			continue
		}

		fi.Write(b)
		f.Close()
	}

	fi.Close()

}
